package com.wangzhixuan.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.commons.utils.PageInfo;
import com.wangzhixuan.model.Skydrive;
import com.wangzhixuan.model.vo.FileFullVo;
import com.wangzhixuan.service.IHistoryService;
import com.wangzhixuan.service.ISkydriveService;
import com.wangzhixuan.service.IUserService;

/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-09-05
 */
@Controller
@RequestMapping("/skydrive")
public class SkydriveController extends BaseController {
    
    @Autowired private ISkydriveService skydriveService;
    
    @Autowired private IHistoryService historyService;
	
    @Autowired private IUserService userService;
    
    @RequestMapping("/manager")
    public String manager() {
        return "skydrive/skydriveList";
    }


    @RequestMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Skydrive skydrive, Integer page, Integer rows, String sort,String order,Integer sId) {       
        if(sId==null){
        	sId = 0;
        }
    	PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        pageInfo.setCondition(condition);
        Skydrive skydrive2 = skydriveService.selectById(sId);
        Integer isShare = skydrive2.getIsShare();
    	Long a = getUserId();
    	long b = a;
    	int c = (int)b;
    	Integer userId = c;
        skydriveService.selectDataGrid(pageInfo,sId,userId,isShare);
        return pageInfo;
    }
    
    
    /**
     * 进入文件夹
     * @param id
     * @return
     */
    @RequestMapping("/getFileFull")
    @ResponseBody
    public FileFullVo getFileFull(@Param("id") String id) {       
     Integer Id = Integer.valueOf(id);
     FileFullVo fileFull = skydriveService.selectFileFull(Id);
     return fileFull;
    }
    
    
    

    /**
     * 创建文件夹
     * @param 
     * @return
     */
    @RequestMapping("/addFile")
    @ResponseBody
    public Object addFile(Integer sId,String fileName,HttpServletRequest request) {
    	Long a = getUserId();
    	long b = a;
    	int c = (int)b;
    	Integer userId = c;
    	Skydrive skydrive = skydriveService.selectById(sId);  //获得父目录的ID
    	if(skydrive==null){
    		return renderError("无法在此目录操作！");
    	}
    	String fileFullName = skydrive.getFileFullName();		//获得完整路径
    	Integer isShare = skydrive.getIsShare();				//获得是否是共享文件夹
    	List<String> fileNames = skydriveService.selectFilName(sId);
    	if(fileNames!=null){
        	for(String fileNameOne : fileNames){
        		if(fileNameOne.equals(fileName)){
        			return renderError("文件夹已存在！");
        		}
        	}
    	}
    	Skydrive skydrive2 = new Skydrive();
    	skydrive2.setCreateId(userId);
    	skydrive2.setCreateTime(new Date());
    	skydrive2.setModifyTime(new Date());
    	skydrive2.setModifyId(userId);
    	skydrive2.setFileFullName(fileFullName+" >> "+fileName);
    	skydrive2.setFileName(fileName);
    	skydrive2.setIsForder(1);
    	skydrive2.setIsShare(isShare);
    	skydrive2.setPid(sId);
        boolean z = skydriveService.insert(skydrive2);
        if (z) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }
    
    /**
     * 添加页面
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage() {
        return "skydrive/skydriveAdd";
    }

    /**
     * 添加
     * @param 
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object add(Skydrive skydrive) {
        boolean b = skydriveService.insert(skydrive);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id,HttpServletRequest request) {
    	if(id==304||id==305){
    		return renderError("无法删除！");
    	}else{
    		long a = (long)id;
    		int b = (int)a;
    		Integer c = (Integer)b;
    		Skydrive selectById = skydriveService.selectById(id);
    		if(selectById.getIsForder()==1){
            	List<Skydrive> son = skydriveService.selectSon(c);
        		if(son.size()!= 0){
        			return renderError("请先删除子文件！");
        		}
    		}
    		Skydrive skydrive = skydriveService.selectById(id);
    		if(skydrive.getIsForder() == 0){
        		String fileUrl = skydrive.getFileUrl();
        		System.out.println(getbaseUrl(request));
        		String replace = fileUrl.replace(getbaseUrl(request),"");
        		String newfileUrl = getRootPath()+replace;
        		System.out.println(newfileUrl);
        		File file = new File(newfileUrl);
        		file.delete();
    		}
            boolean tf = skydriveService.deleteById(id);
            if (tf) {
                return renderSuccess("删除成功！");
            } else {
                return renderError("删除失败！");
            }
    	}
    }

    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, Long id) {
        Skydrive skydrive = skydriveService.selectById(id);
        model.addAttribute("skydrive", skydrive);
        return "skydrive/skydriveEdit";
    }

    
    /**
     * 编辑
     * @param 
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(Skydrive skydrive) {
        boolean b = skydriveService.updateById(skydrive);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }
    
    /**
     * 回退
     * @param sId
     * @return
     */
    @RequestMapping("/back")
    @ResponseBody
    public FileFullVo back(Integer sId) {
        Skydrive skydrive = skydriveService.selectById(sId);
        Integer pid = skydrive.getPid();
        Skydrive skydrive2 = skydriveService.selectById(pid);
        String fileFullName = skydrive2.getFileFullName();
         FileFullVo fileFullVo = new FileFullVo();
         fileFullVo.setsId(pid);            //实际上应该放入sId,这里将就用一下
         fileFullVo.setFileFullName(fileFullName);
        return fileFullVo;
    }

    
    /**
     * 上传页面
     * @param id
     * @return
     */
    @RequestMapping("/fileUploadPage")
    public String fileUploadPage() {
     return "skydrive/skydriveUpload";
    }
    
    /**
     * 文件上传
     * @param id
     * @return
     * @throws Exception 
     * @throws IOException 
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Object fileUpLoad(Integer pId,@RequestParam("fileUpload") MultipartFile fileUpload,
    		HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {   
    	Long a = getUserId();
    	long b = a;
    	int c = (int)b;
    	Integer userId = c;
    	System.out.println("获取用户ID"+userId);
    	if (pId == null  ) {
    		return renderError("无法在此目录操作!");
		}
		if (fileUpload == null) {
			return renderError("网络异常请稍后再试!");
		}
    	Skydrive pSkydrive = skydriveService.selectById(pId);
    	if(pSkydrive==null){
    		return renderError("父文件夹不存在，不能上传文件夹!");
    	}
    	if(pSkydrive.getIsShare()==1&&pSkydrive.getCreateId()!=userId){
    		if(pId!=305){
    			return renderError("您没有操作此文件夹的权限"); 
    		}
    	}
    	if(fileUpload.isEmpty()){  
    		return renderError("选择文件后上传!");
    	}
    	saveFiles(fileUpload, request,userId,pId,pSkydrive);           //文件上传
    	return renderSuccess("添加成功！");
    }
    
	private void saveFiles( MultipartFile myfile, HttpServletRequest request,
			Integer userId,Integer fileId,Skydrive pSkydrive)
			throws Exception, IOException {
		String pathRoot = getRootPath();
		String filePath = mkdirs(pathRoot,userId);
		new File(filePath).mkdirs();
		Skydrive skydrive = new Skydrive();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");
		Date date2 = new Date();
		//System.out.println(myfile.getOriginalFilename());
		String Filename = myfile.getOriginalFilename();
		String tempfilePath = filePath + Filename;
		String format4 = format.format(date2);
		File fileUpload = new File(pathRoot + filePath+format4+myfile.getOriginalFilename().substring(          //获得后缀名
				myfile.getOriginalFilename().lastIndexOf(".")));
		String fileSuffixName = myfile.getOriginalFilename().substring(          //获得后缀名
		myfile.getOriginalFilename().lastIndexOf("."));
		if(fileUpload.exists()){
			String format2 = format.format(date2);
			Filename =  format2+"_"+Filename ;
			tempfilePath = filePath + Filename;
			fileUpload = new File(pathRoot + filePath+format2+myfile.getOriginalFilename().substring(          //获得后缀名
					myfile.getOriginalFilename().lastIndexOf(".")));
		}
		myfile.transferTo(fileUpload);											//=================================上传=========================
		String format3 = format.format(date2);
		String URL = getbaseUrl(request) + filePath+format3+myfile.getOriginalFilename().substring(          //获得后缀名
				myfile.getOriginalFilename().lastIndexOf("."));				//获得URL
		skydrive.setSmallPictureUrl("");                                    //先设置缩略图为""
		skydrive.setFileSuffixName(fileSuffixName);
		skydrive.setCreateId(userId);
		skydrive.setCreateTime(date);
		skydrive.setModifyTime(date);
		skydrive.setFileFullName(pSkydrive.getFileFullName()+">>>"+Filename);
		skydrive.setFileName(Filename);
		skydrive.setFileUrl(URL);
		skydrive.setIsForder(0);
		skydrive.setIsShare(pSkydrive.getIsShare());
		skydrive.setPid(fileId);
		skydrive.setUploadSize(1);
		skydriveService.insert(skydrive);
	}
    
	private String mkdirs(String pathRoot,Integer userId) {
		Date date = new Date();
		StringBuffer path = new StringBuffer();
		path.append("CloudDisk/").append(new SimpleDateFormat("yyyy/MM/dd").format(date))
				.append("/Id_"+userId+"/");
		File f = new File(pathRoot + path.toString());
		if (!f.exists())
			f.mkdirs();
		return path.toString();
	}
	
	
    /**
     * 下载
     * @param model
     * @param id
     * @return
     * @throws IOException 
     */
    @RequestMapping("/downloadPage")
    public String downloadPage() {
    	return "skydrive/skydriveDown";
    }
    /**
     * 下载
     * @param model
     * @param id
     * @return
     * @throws IOException 
     */
    @RequestMapping("/GTEdownload")
    @ResponseBody
    public Skydrive download(Integer id){
    	System.out.println("id:"+id);
        Skydrive skydrive = skydriveService.selectById(id);
        
        return skydrive;
    }

}
